package com.chinawlx.wlxteacher.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.base.WLXApplication;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXClazzHomeWorkBean;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.network.bean.WLXHomeWorkCommentBean;
import com.chinawlx.wlxteacher.ui.fragment.WLXLoadingFragment;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.nine_grid.WLXGridLayout;
import com.chinawlx.wlxteacher.widget.record.AudioRecordButton;
import com.chinawlx.wlxteacher.widget.record.MediaManager;
import com.chinawlx.wlxteacher.wlx_homework_comment;
import com.chinawlx.wlxteacher.wlx_homework_commentDao;
import com.chinawlx.wlxteacher.wlx_student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;

/**
 * 家长回复
 * TODO 代码逻辑整理，代码重构->UI界面优化
 */
public class WLXParentRplyctivity extends WLXBaseActivity {
    @BindView(R.id.iv_voice_inport)
    ImageView ivVoiceInport;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.rl_import)
    LinearLayout rlImport;
    @BindView(R.id.lv_speak_list)
    ListView lvSpeakList;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.btnRecord)
    AudioRecordButton mBtnRecord;
    @BindView(R.id.send_msg)
    TextView mSendMsg;
    @BindView(R.id.tv_msg)
    TextView mTVMsg;
    @BindView(R.id.rl_container_empty)
    RelativeLayout mRlContainerEmpty;//空白区域


    private InputMethodManager mImm;//输入法管理器

    private List<wlx_homework_comment> commentList;
    private List<wlx_homework_comment> commentAllList;
    private String homework_id;
    private String student_id;
    private String time, content, before_extend_info, homework_content_code;
    //头部学生作业信息
    private WLXClazzHomeWorkBean.DataBean.HomeworkListBean.ExtendBean extendBedoreBean;
    private View heardview;
    private TextView tvTimeTip;
    private Long creatData;
    public static String mUserIconUrl;//学生用户头像

    private HomeworkAdapter mHomeworkAdapter;//聊天列表适配器
    private int currentPlayPosition = -1;//当前正在播放的position
    private WLXGridLayout mNineGridLayout;
    private ImageView mIvVideoImg;
    private ImageView mIvVideoCover;
    private RelativeLayout mRlVideoContainer;
    private WLXLoadingFragment mLoadingFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wlxparent_rplyctivity);
        ButterKnife.bind(this);

        mLoadingFragment = WLXLoadingFragment.getInstance();
        checkAutoPermission();
        mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        init();
    }

    //录音完成后的回调,处理逻辑
    class MyAudioRecordFinishListener implements AudioRecordButton.AudioRecordFinishListener {

        @Override
        public void onFinish(float second, String filePath) {
            Log.d("byron", Math.round(second) + "s,path:" + filePath);
            WLXHttpRxHelper.getInstance().teacherCommentAdd(homework_id, content, "audio", Math
                    .round(second)
                    + "", new File(filePath), new Subscriber<WLXGetCodeBean>() {

                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    WLXCustomToast.show("语音发送失败,请检查网络后重试!");
                }

                @Override
                public void onNext(WLXGetCodeBean bean) {
                    if (bean.getCode() == 0) {
                        initData();
                    } else {
                        WLXCustomToast.show(bean.getMsg());
                    }
                }
            });
        }
    }

    //----------------------------6.0权限检查-------------------------------------
    private void checkAutoPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.RECORD_AUDIO},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                Log.d("Home", "Already granted access");
            }
        }
    }

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 29;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("Home", "Permission Granted");
                } else {
                    Log.d("Home", "Permission Failed");
                    Toast.makeText(getApplicationContext(), "You must allow permission record " +
                            "audio to your mobile device.", Toast.LENGTH_SHORT).show();
                }
            }
            // Add additional cases for other permissions you may have asked for
        }
    }
    //--------------------------6.0权限检查--------------------------------

    //初始化数据
    private void init() {

        initPassValue();
        initView();
        initSpeakList();
        initData();
    }

    private void initPassValue() {
        mBtnRecord.setAudioRecordFinishListener(new MyAudioRecordFinishListener());
        homework_id = getIntent().getStringExtra("homework_id");
        student_id = getIntent().getStringExtra("student_id");
        time = getIntent().getStringExtra("time");
        homework_content_code = getIntent().getStringExtra("homework_content_code");
        content = getIntent().getStringExtra("content");
        before_extend_info = getIntent().getStringExtra("extend_info");
        mUserIconUrl = getIntent().getStringExtra("userIcon");
    }

    private void initSpeakList() {
        lvSpeakList.addHeaderView(heardview);
        mHomeworkAdapter = new HomeworkAdapter();
        lvSpeakList.setAdapter(mHomeworkAdapter);
    }

    private void initView() {
        extendBedoreBean = new Gson().fromJson(before_extend_info, new
                TypeToken<WLXClazzHomeWorkBean.DataBean.HomeworkListBean.ExtendBean>() {
                }.getType());
        Log.d("-------", before_extend_info);
        //头部学生作业信息
        heardview = LayoutInflater.from(this).inflate(R.layout.head_home_work_comment, null);
        tvTimeTip = (TextView) heardview.findViewById(R.id.tv_time_tip);//时间
        CircleImageView tipCIUserPhoto = (CircleImageView) heardview.findViewById(R.id
                .tip_user_photo);
        TextView tipTvUserName = (TextView) heardview.findViewById(R.id.tip_tv_user_name);
        TextView tipTvTime = (TextView) heardview.findViewById(R.id.tip_tv_time);
        TextView tipUserContent = (TextView) heardview.findViewById(R.id.tip_user_content);
        mNineGridLayout = (WLXGridLayout) heardview.findViewById(R.id.layout_nine_grid);
        mRlVideoContainer = (RelativeLayout) heardview.findViewById(R.id
                .rl_video_container);
        mIvVideoImg = (ImageView) heardview.findViewById(R.id.iv_video_img);
        mIvVideoCover = (ImageView) heardview.findViewById(R.id.iv_video_cover);

        tipTvTime.setText(time);
        wlx_student student = WLXGreenDaoUtil.getStudentDao().load(student_id);
        tipTvUserName.setText(student.getRealname());
        tipUserContent.setText(content);
        Glide.with(this).load(student.getAvatar_url()).into(tipCIUserPhoto);

        //设置用户发布图片

        //url数量
        List<String> urls = extendBedoreBean.getResource_url();
        if (urls.size() > 0) {
            switch (homework_content_code) {
                case "image":
                    mRlVideoContainer.setVisibility(View.GONE);
                    mNineGridLayout.setVisibility(View.VISIBLE);
                    mNineGridLayout.setUrlList(urls);
                    break;
                case "video":
                    mRlVideoContainer.setVisibility(View.VISIBLE);
                    mNineGridLayout.setVisibility(View.GONE);

                    final String videoUrl = urls.get(0);
                    String picture = videoUrl.replace("mp4", "png");
                    Glide.with(this).load(picture).placeholder(R.drawable
                            .place_holder).centerCrop().into(mIvVideoImg);

                    mIvVideoCover.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(WLXParentRplyctivity.this,
                                    WLXPlayVideoActivity.class);
                            intent.putExtra(WLXPlayVideoActivity.VIDEO_URL, videoUrl);
                            startActivity(intent);
                        }
                    });
                    break;
            }
        }
    }

    private void initData() {
        mLoadingFragment.show(getSupportFragmentManager(), "parentRply");
        WLXHttpRxHelper.getInstance().getHomeWorkComment(homework_id, "", new
                Subscriber<WLXHomeWorkCommentBean>() {
                    @Override
                    public void onCompleted() {
                        initDataForDataBase();
                        mLoadingFragment.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {

                        onCompleted();
                    }

                    @Override
                    public void onNext(WLXHomeWorkCommentBean wlxHomeWorkCommentBean) {
                        insert2Db(wlxHomeWorkCommentBean);
                    }
                });
    }

    //插入数据到数据库中
    private void insert2Db(WLXHomeWorkCommentBean wlxHomeWorkCommentBean) {

        List<WLXHomeWorkCommentBean.DataBean> homeworkcomment_list =
                wlxHomeWorkCommentBean.getData();
        WLXLogUtil.printE("homeworkcomment_list条数:" + homeworkcomment_list.size());
        for (WLXHomeWorkCommentBean.DataBean homeworkcomment :
                homeworkcomment_list) {
            String homework_comment_id = Integer.toString(homeworkcomment.getId());
            WLXConstant.HOMEWORK_COMMENT_ID = homework_comment_id;
            int homework_id = homeworkcomment.getHomework_id();
            int user_id = homeworkcomment.getUser_id();
            String content = homeworkcomment.getContent();
            int is_teacher = homeworkcomment.isIs_teacher() ? 1 : 0;
            String extend_info = new Gson().toJson(homeworkcomment.getExtend());
            String comment_content_code = homeworkcomment.getComment_content_code
                    ().getKey();
            long creation_date = WLXDateUtil.getStringToDate(homeworkcomment
                    .getCreation_date());
            long last_modified_date = WLXDateUtil.getStringToDate(homeworkcomment
                    .getLast_modified_date());
            //插入作业数据
            wlx_homework_comment wlxHomeWorkComment = new wlx_homework_comment
                    (homework_comment_id, homework_id, user_id,
                            content,
                            is_teacher, extend_info,
                            comment_content_code, creation_date,
                            last_modified_date);
            //1,查询homework_comment_id这条记录,homework_comment_id是唯一的
            List<wlx_homework_comment> wlx_homework_comments = WLXGreenDaoUtil
                    .getHomeWorCommentkDao()
                    .queryBuilder()
                    .where(wlx_homework_commentDao
                            .Properties.Homework_comment_id.eq(WLXConstant
                                    .HOMEWORK_COMMENT_ID)).list();
            if (wlx_homework_comments.size() > 0) {
                //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                if (last_modified_date > wlx_homework_comments.get(0)
                        .getLast_modified_date()) {
                    WLXGreenDaoUtil.getHomeWorCommentkDao().update
                            (wlxHomeWorkComment);
                }
            } else {
                //无数据,就直接插入数据
                WLXGreenDaoUtil.getHomeWorCommentkDao().insert(wlxHomeWorkComment);
            }
        }
    }

    //初始化家长回复列表的对话项目
    private void initDataForDataBase() {
        //所有的回复数据
        commentAllList = WLXGreenDaoUtil.getHomeWorCommentkDao().queryBuilder().orderAsc
                (wlx_homework_commentDao.Properties.Creation_date).list();
        if (commentAllList != null) {
            commentList = WLXGreenDaoUtil.getHomeWorCommentkDao().queryBuilder().where
                    (wlx_homework_commentDao.Properties.Homework_id.eq(homework_id)).orderAsc
                    (wlx_homework_commentDao.Properties.Creation_date).list();
            if (commentList.size() > 0) {
                tvTimeTip.setVisibility(View.VISIBLE);
                long current_time = System.currentTimeMillis() / 1000L;//TODO 时间有点小问题,显示一分钟后,,,
                creatData = commentList.get(commentList.size() - 1).getCreation_date();
                //获取现在时间和创始时间的差值
                String time = WLXDateUtil.getDistanceTime(creatData, current_time);
                tvTimeTip.setText(time);
            } else {
                tvTimeTip.setVisibility(View.GONE);
            }
        }

        mHomeworkAdapter.notifyDataSetChanged();
        lvSpeakList.setSelection(mHomeworkAdapter.getCount());
    }

    private boolean voiceIconShow = true;//当前是voice图标在显示

    @OnClick({R.id.iv_back, R.id.iv_voice_inport, R.id.send_msg})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_voice_inport:
                if (voiceIconShow) {
                    mImm.hideSoftInputFromWindow(rlImport.getWindowToken(), 0);
                    ivVoiceInport.setImageResource(R.drawable.keyboard);
                    mBtnRecord.setVisibility(View.VISIBLE);
                    mSendMsg.setVisibility(View.GONE);
                    etInput.setVisibility(View.GONE);
                    voiceIconShow = false;
                } else {
                    ivVoiceInport.setImageResource(R.drawable.voice);
                    mBtnRecord.setVisibility(View.GONE);
                    mSendMsg.setVisibility(View.VISIBLE);
                    etInput.setVisibility(View.VISIBLE);
                    voiceIconShow = true;
                }
                break;
            case R.id.send_msg:
                String msg = etInput.getText().toString();
                if (TextUtils.isEmpty(msg)) {
                    WLXCustomToast.show("内容不能为空");
                    return;
                }
                sendText(msg);
                break;
        }
    }

    //发送消息
    private void sendText(String msg) {
        WLXHttpRxHelper.getInstance().teacherCommentAdd(homework_id, msg, "text", "0",
                null, new Subscriber<WLXGetCodeBean>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        WLXCustomToast.show("发送失败,请检查网络");
                    }

                    @Override
                    public void onNext(WLXGetCodeBean bean) {
                        if (bean.getCode() == 0) {
                            etInput.setText("");
                            initData();
                        } else {
                            WLXCustomToast.show(bean.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        //音频要停止播放
        currentPlayPosition = -1;
        MediaManager.release();
    }

    //聊天列表的适配器
    class HomeworkAdapter extends BaseAdapter {
        public static final int VALUE_LEFT_TEXT = 0;
        public static final int VALUE_RIGHT_TEXT = 1;
        public static final int VALUE_LEFT_AUDIO = 2;
        public static final int VALUE_RIGHT_AUDIO = 3;

        @Override
        public int getCount() {
            return commentList == null ? 0 : commentList.size();
        }

        @Override
        public Object getItem(int position) {
            return commentList.get(position);
        }

        //获取对话类型
        @Override
        public int getItemViewType(int position) {
            creatData = commentList.get(position).getCreation_date();
            if (commentList.get(position).getIs_teacher() == 0) {
                if (commentList.get(position).getComment_content_code().equals("audio")) {
                    return VALUE_LEFT_AUDIO;
                } else {
                    return VALUE_LEFT_TEXT;
                }
            } else if (commentList.get(position).getIs_teacher() == 1) {
                if (commentList.get(position).getComment_content_code().equals("audio")) {
                    return VALUE_RIGHT_AUDIO;
                } else {
                    return VALUE_RIGHT_TEXT;
                }
            }
            return -1;
        }

        @Override
        public int getViewTypeCount() {
            return 4;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            ViewHolderRightText holderRightText = null;
            ViewHolderRightAudio holderRightAudio = null;
            ViewHolderLeftText holderLeftText = null;
            ViewHolderLeftAudio holderLeftAudio = null;
            WLXHomeWorkCommentBean.DataBean.ExtendBean extendBean = null;

            wlx_homework_comment wlx_homework_comment = commentList.get(position);
            if (convertView == null) {
                String extend_info = wlx_homework_comment.getExtend_info();
                WLXLogUtil.i("--------------------------------" + extend_info);

                extendBean = new Gson().fromJson(extend_info, new
                        TypeToken<WLXHomeWorkCommentBean.DataBean.ExtendBean>() {
                        }.getType());

                switch (type) {
                    //左边文字对话
                    case VALUE_LEFT_TEXT:
                        holderLeftText = new ViewHolderLeftText();
                        convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout
                                .list_item_left_text, parent, false);
                        holderLeftText.ivLeftIcon = (CircleImageView) convertView.findViewById(R
                                .id.user_photo);
                        holderLeftText.btnLeftText = (TextView) convertView.findViewById(R.id
                                .tv_left_text);

                        convertView.setTag(holderLeftText);
                        break;
                    //右边文字对话
                    case VALUE_RIGHT_TEXT:
                        holderRightText = new ViewHolderRightText();
                        convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout
                                .list_item_right_text, parent, false);
                        holderRightText.ivRightIcon = (CircleImageView) convertView.findViewById
                                (R.id.teacher_photo);
                        holderRightText.tvRightText = (TextView) convertView.findViewById(R.id
                                .list_right_text);
                        convertView.setTag(holderRightText);
                        break;

                    //左边语音对话
                    case VALUE_LEFT_AUDIO:
                        holderLeftAudio = new ViewHolderLeftAudio();
                        convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout
                                .list_item_left_audio, parent, false);
                        holderLeftAudio.ivLeftIcon = (CircleImageView) convertView.findViewById(R
                                .id.user_photo);
                        holderLeftAudio.tvLeftAudioTime = (TextView) convertView.findViewById(R
                                .id.tv_voice_long);

                        convertView.setTag(holderLeftAudio);
                        break;
                    //右边语音对话
                    case VALUE_RIGHT_AUDIO:
                        holderRightAudio = new ViewHolderRightAudio();
                        convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout
                                .list_item_right_audio, parent, false);
                        holderRightAudio.ivRightIcon = (CircleImageView) convertView.findViewById
                                (R.id.teacher_photo);
                        holderRightAudio.tvRightAudioTime = (TextView) convertView.findViewById(R
                                .id.tv_right_voice);

                        convertView.setTag(holderRightAudio);
                        break;
                }
            } else {
                switch (type) {

                    case VALUE_LEFT_TEXT:
                        holderLeftText = (ViewHolderLeftText) convertView.getTag();
                        break;
                    case VALUE_RIGHT_TEXT:
                        holderRightText = (ViewHolderRightText) convertView.getTag();
                        break;
                    case VALUE_LEFT_AUDIO:
                        holderLeftAudio = (ViewHolderLeftAudio) convertView.getTag();
                        break;
                    case VALUE_RIGHT_AUDIO:
                        holderRightAudio = (ViewHolderRightAudio) convertView.getTag();
                        break;
                }
            }

            //----------------------数据处理-------------------
            switch (type) {
                case VALUE_LEFT_TEXT:
                    if (mUserIconUrl != null) {

                        Glide.with(getApplicationContext()).load(mUserIconUrl)
                                .into
                                        (holderLeftText.ivLeftIcon);
                    }
                    holderLeftText.btnLeftText.setText(commentList.get(position).getContent());
                    break;
                case VALUE_RIGHT_TEXT:

                    Glide.with(getApplicationContext()).load(WLXApplication.mActiveUser
                            .getAvatar_url())
                            .into
                                    (holderRightText.ivRightIcon);
                    holderRightText.tvRightText.setText(commentList.get(position).getContent());
                    break;
                case VALUE_LEFT_AUDIO:
                    if (currentPlayPosition == position) {
                        holderLeftAudio.tvLeftAudioTime.setBackgroundResource(R.drawable
                                .voiceplaying);
                    } else {
                        holderLeftAudio.tvLeftAudioTime.setBackgroundResource(R.drawable
                                .voiceplayback);
                    }
                    //设置语音时间
                    if (mUserIconUrl != null) {
                        Glide.with(getApplicationContext()).load(mUserIconUrl)
                                .into
                                        (holderLeftAudio.ivLeftIcon);
                    }
                    if (extendBean != null) {
                        holderLeftAudio.tvLeftAudioTime.setText(extendBean
                                .getDuration() + "“");
                    }
                    final ViewHolderLeftAudio finalHolderLeftAudio = holderLeftAudio;
                    final WLXHomeWorkCommentBean.DataBean.ExtendBean finalExtendBean = extendBean;
                    holderLeftAudio.tvLeftAudioTime.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (currentPlayPosition == position) {
                                //表示当前正在播放,暂停下来
                                MediaManager.release();
                                currentPlayPosition = -1;
                                finalHolderLeftAudio.tvLeftAudioTime.setBackgroundResource(R
                                        .drawable
                                        .voiceplayback);
                                return;
                            }

                            currentPlayPosition = position;
                            notifyDataSetChanged();//将其它的偶变成不是播放状态

                            try {
                                String path = finalExtendBean.getResource_url().get(0);
                                if (path.endsWith(".caf")) {
                                    Toast.makeText(getApplicationContext()
                                            , "caf格式无法播放", Toast.LENGTH_SHORT)
                                            .show();
                                    currentPlayPosition = -1;
                                    finalHolderLeftAudio.tvLeftAudioTime.setBackgroundResource(R
                                            .drawable
                                            .voiceplayback);
                                    return;
                                }
                                MediaManager.playSound(path, new
                                        MediaPlayer.OnCompletionListener() {
                                            @Override
                                            public void onCompletion(MediaPlayer mp) {
                                                currentPlayPosition = -1;
                                                finalHolderLeftAudio.tvLeftAudioTime
                                                        .setBackgroundResource(R.drawable
                                                                .voiceplayback);
                                            }
                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext()
                                        , "语音播放失败", Toast.LENGTH_SHORT)
                                        .show();
                                currentPlayPosition = -1;
                                finalHolderLeftAudio.tvLeftAudioTime.setBackgroundResource(R
                                        .drawable
                                        .voiceplayback);
                            }
                        }
                    });
                    break;
                case VALUE_RIGHT_AUDIO:
                    if (currentPlayPosition == position) {
                        //正在播放
                        holderRightAudio.tvRightAudioTime.setBackgroundResource(R.drawable
                                .voiceplayback);
                    } else {
                        //没播放的
                        holderRightAudio.tvRightAudioTime.setBackgroundResource(R.drawable
                                .voiceplayback);
                    }

                    Glide.with(getApplicationContext()).load(WLXApplication.mActiveUser
                            .getAvatar_url())
                            .into
                                    (holderRightAudio.ivRightIcon);

                    if (extendBean != null) {
                        holderRightAudio.tvRightAudioTime.setText(extendBean
                                .getDuration() + "“");
                    }
                    final ViewHolderRightAudio finalHolderRightAudio = holderRightAudio;
                    final WLXHomeWorkCommentBean.DataBean.ExtendBean finalExtendBean1 = extendBean;
                    holderRightAudio.tvRightAudioTime.setOnClickListener(new View.OnClickListener
                            () {
                        @Override
                        public void onClick(View v) {
                            if (currentPlayPosition == position) {
                                //表示当前正在播放,暂停下来
                                MediaManager.release();
                                currentPlayPosition = -1;
                                finalHolderRightAudio.tvRightAudioTime
                                        .setBackgroundResource(R
                                                .drawable
                                                .voiceplayback);
                                return;
                            }

                            currentPlayPosition = position;
                            notifyDataSetChanged();
                            try {
                                String path = finalExtendBean1.getResource_url().get(0);
                                if (path.endsWith(".caf")) {
                                    Toast.makeText(getApplicationContext()
                                            , "caf格式无法播放", Toast.LENGTH_SHORT)
                                            .show();
                                    currentPlayPosition = -1;
                                    finalHolderRightAudio.tvRightAudioTime
                                            .setBackgroundResource(R
                                                    .drawable
                                                    .voiceplayback);
                                    return;
                                }
                                MediaManager.playSound(path, new
                                        MediaPlayer.OnCompletionListener() {
                                            @Override
                                            public void onCompletion(MediaPlayer mp) {
                                                //播放完成,UI改回来
                                                currentPlayPosition = -1;
                                                finalHolderRightAudio.tvRightAudioTime
                                                        .setBackgroundResource(R
                                                                .drawable
                                                                .voiceplayback);
                                            }
                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext()
                                        , "语音播放失败", Toast.LENGTH_SHORT)
                                        .show();
                                currentPlayPosition = -1;
                                finalHolderRightAudio.tvRightAudioTime.setBackgroundResource(R
                                        .drawable
                                        .voiceplayback);
                            }
                        }
                    });
                    break;
            }
            return convertView;
        }

        class ViewHolderRightText {
            private CircleImageView ivRightIcon;// 右边的头像
            private TextView tvRightText;// 右边的文本
        }

        class ViewHolderRightAudio {
            private CircleImageView ivRightIcon;// 右边的头像
            private TextView tvRightAudioTime;// 右边的声音时间
        }

        class ViewHolderLeftText {
            private CircleImageView ivLeftIcon;// 左边的头像
            private TextView btnLeftText;// 左边的文本
        }

        class ViewHolderLeftAudio {
            private CircleImageView ivLeftIcon;// 左边的头像
            private TextView tvLeftAudioTime;// 左边的声音时间
        }
    }

}

